package nio.application;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Desc:   模拟 TCP 服务端
 * @author: cww
 * @DateTime: 2020-02-05 23:38
 */

public class TcpServer {
    public static void main(String[] args) throws Exception {
        System.out.println("socket tcp 服务端启动");
        ServerSocket serverSocket = new ServerSocket(7777);
        // 等待客户端请求
        try {
            while (true) {
                Socket accept = serverSocket.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream inputStream = accept.getInputStream();
                            byte[] buf = new byte[1024];
                            inputStream.read(buf);
                            System.out.println("服务器接收客户端内容：" + new String(buf));
                        } catch (IOException e) {
                            System.out.println("服务端异常");
                        }
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }
}
